package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.dto.RequestParams;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.vo.PageResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 分页条件查询
     * 1.酒店关键字搜索
     * 2.分页
     *
     * @param requestParams
     * @return
     */
    @Override
    public PageResult pageList(RequestParams requestParams) throws IOException {
        //1.创建搜索对象
        SearchRequest request = new SearchRequest("hotel");
        buildDSL(requestParams, request);
        //2.发送请求 进行搜索
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //3.解析结果
        return getPageResult(response);
    }

    /**
     * 解析响应对象 封装分页结果给页面
     *
     * @param response
     * @return
     */
    private static PageResult getPageResult(SearchResponse response) {
        SearchHits sh = response.getHits();//最外层的hits
        long total = sh.getTotalHits().value;//总记录数

        SearchHit[] hits = sh.getHits();
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);

            //黑马旅游案例-我附近的酒店 第四步 解析DSL结果得到距离 设置到hotelDoc对象中
            Object[] sortValues = hit.getSortValues();
            if (sortValues != null && sortValues.length > 0) {
                Object sortValue = sortValues[0];
                if (sortValue != null)
                    hotelDoc.setDistance(sortValue);
            }

            //高亮处理
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(!CollectionUtils.isEmpty(highlightFields)){
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField != null){
                    String newName = highlightField.getFragments()[0].string();
                    hotelDoc.setName(newName);//将高亮标签中的结果 设置到返回给页面的对象中
                }
            }
            hotels.add(hotelDoc);
        }
        //4.封装PageResult分页对象给页面
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setHotels(hotels);
        return pageResult;
    }

    /**
     * 构建DSL
     *
     * @param requestParams
     * @param request
     */
    private static void buildDSL(RequestParams requestParams, SearchRequest request) {
        //1.1 获取请求对象中所有参数
        Integer page = requestParams.getPage();//页码
        Integer size = requestParams.getSize();//每页条数
        String key = requestParams.getKey();//名称
        String sortBy = requestParams.getSortBy();//排序 default score price
        String city = requestParams.getCity();//城市
        String brand = requestParams.getBrand();//品牌
        Integer maxPrice = requestParams.getMaxPrice();//最大值
        Integer minPrice = requestParams.getMinPrice();//最小值
        String starName = requestParams.getStarName();//星级
        String location = requestParams.getLocation();//当前用户经纬度
        //1.2 构建DSL参数
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (StringUtils.isEmpty(key)) { //如果为空，则查询全部
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }

        //1.3 黑马旅游案例-条件过滤（品牌 城市 价格 星级）
        if (!StringUtils.isEmpty(city)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("city", city));
        }
        if (!StringUtils.isEmpty(brand)) {
            boolQueryBuilder.should(QueryBuilders.termQuery("brand", brand));
        }
        if (!StringUtils.isEmpty(maxPrice)) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice));
        }
        if (!StringUtils.isEmpty(minPrice)) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }
        if (!StringUtils.isEmpty(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
        if(!StringUtils.isEmpty(location)) {
            //1.4  黑马旅游案例-我附近的酒店 第二步 构建根据地址位置进行搜索
            request.source().sort(
                    SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
            );
        }
        //1.5 算分函数 为文档进行加分
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true), //算分函数的过滤条件 满足条件才会加分
                                ScoreFunctionBuilders.weightFactorFunction(5)    //权重多少分
                        )
                }
        );//.boostMode(CombineFunction.SUM)  默认 query_score分数 * function_score 相乘

        //1.6 评价降序 价格升序
        if(sortBy.equals("score")){
            request.source().sort("score", SortOrder.DESC);
        }else if(sortBy.equals("price")){
            request.source().sort("price",SortOrder.ASC);
        }
        //1.7 高亮设置
        request.source().highlighter(
                new HighlightBuilder().field("name")
                        .requireFieldMatch(false)
        );
        //1.8 分页参数
        request.source().from((page - 1) * size).size(size);//第一页0,5 第二页 5,5
        request.source().query(functionScoreQueryBuilder);
    }

}
